#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include"inc/game.h"
#include"inc/app.h"
#include"inc/game.h"
#include"inc/pthread.h"
#include"lv_mygec_font.h"
#include"lv_conf.h"
lv_obj_t *info_label = NULL;
int game_over = 0; 
Gnode *create_doublelist()
{
	Gnode*p = (Gnode *)malloc(sizeof(*p));
    p->first = NULL;	//	指向单链表的第一个结点(空链表)
    p->last = NULL;     //指向最后一个结点
    p->num = 0;		//	链表的结点数
    return p;
}


void add_chess(Gnode  *l,int x, int y,int full,int type, lv_obj_t *img)//棋子
{
	if(l)	
	{
		//	1、给新元素分配动态 结点空间
		Node *newp = malloc(sizeof(Node));
		newp->x = x;
        newp->y = y;
        newp->full= full;
        newp->type=type;
        newp->img=img;
		newp->next = NULL;				
        newp->prev=NULL;
		//	2、无中生有
		if(l->num== 0)			
		{
			l->first =  l->last= newp;
            
		}
		
		//	3、有元素继续插入
		else
		{
            l->last->next = newp;
            newp->prev = l->last;
           
            l->last = newp;
             			
			
		}	
		l->num ++;	
	}
    
}

 

lv_obj_t* board;
lv_obj_t *chess_bg;
// 创建棋盘
void create_chessboard(lv_obj_t* parent) 
{
    // 棋盘背景
     board = lv_obj_create(parent);
    lv_obj_set_size(board, 480, 480);
    lv_obj_set_pos(board, 0, 0);
    lv_obj_set_style_bg_color(board, lv_color_hex(0xD2B48C), LV_PART_MAIN);
    lv_obj_set_style_border_width(board, 0, LV_PART_MAIN);
    lv_obj_set_style_radius(board, 0, LV_PART_MAIN);
     lv_obj_add_event_cb(board,get_point_cb,LV_EVENT_CLICKED,NULL);
    
 chess_bg= lv_img_create(lv_scr_act());
   lv_img_set_src(chess_bg, "A:/tzh/bg.bmp");
}


void get_point_cb(lv_event_t *e)//获取棋子坐标
{
   // pthread_mutex_lock(&ui_mutex);
    if (game_over) {
        printf("Game over! Cannot place more pieces.\n");
        return;
    }
    if (!global_list) return;
    lv_point_t point;
    lv_indev_get_point(lv_indev_active(), &point);  // 获取输入设备的点击坐标
    //printf("(%d,%d)\n", point.x, point.y);
    
    // 计算网格对齐后的坐标
    int grid_x = (point.x / 32) * 32;
    int grid_y = (point.y / 32) * 32;
    
     // 计算棋盘位置索引
    int board_x = point.x / 32;
    int board_y = point.y / 32;
    
    // 边界检查
    if (board_x < 0 || board_x >= 15 || board_y < 0 || board_y >= 15) 
    {
        printf("Position out of board!\n");
        return;
    }
    
    // 检查位置是否已被占用
    if (board_state[board_y][board_x] != 0) 
    {
        printf("Position occupied!\n");
        return;
    }
    
    // 创建图片对象 
     lv_obj_t * chess_img = lv_img_create(lv_scr_act());
   
    
    // 确定棋子类型
    int chess_type;
    if (global_list->first == NULL)
    {
        chess_type = 0;  // 黑棋
    } else if (global_list->last->type == 0) 
    {
        chess_type = 1;  // 白棋
    } else {
        chess_type = 0;  // 黑棋
    }
    
    // 设置棋子图片
    if (chess_type == 0) 
    {
        lv_img_set_src(chess_img, "A:/tzh/b.bmp");
    } else
    {

        lv_img_set_src(chess_img, "A:/tzh/w.bmp");
    }
    
    // 设置棋子位置
    lv_obj_set_pos(chess_img, grid_x, grid_y);
    
    // 添加棋子到链表
    add_chess(global_list, grid_x, grid_y, 1, chess_type, chess_img);
    
    // 更新棋盘状态
    board_state[board_y][board_x] = chess_type + 1;
     update_game_info();
   // pthread_mutex_unlock(&ui_mutex);
}


extern const lv_font_t lv_mygec_font;
lv_obj_t* panel;
// 创建控制面板
void create_control_panel(lv_obj_t* parent)
{
    static lv_style_t style_obj;
    lv_style_init(&style_obj);
    // 面板背景
     panel = lv_obj_create(parent);
    lv_obj_set_size(panel, 320, 480);
    lv_obj_set_pos(panel, 480, 0);
    lv_obj_set_style_bg_color(panel, lv_color_hex(0xF5F5F5), LV_PART_MAIN);
    lv_obj_set_style_border_width(panel, 0, LV_PART_MAIN);
    lv_obj_set_style_pad_all(panel, 20, LV_PART_MAIN);
    


    // 按钮容器
    lv_obj_t* btn_cont = lv_obj_create(panel);
    lv_obj_set_size(btn_cont, 320 - 40, 220);
    lv_obj_align(btn_cont, LV_ALIGN_TOP_MID, 0, 60);
    lv_obj_set_flex_flow(btn_cont, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(btn_cont, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_set_style_bg_opa(btn_cont, LV_OPA_TRANSP, LV_PART_MAIN);
    lv_obj_set_style_border_width(btn_cont, 0, LV_PART_MAIN);
    lv_obj_set_style_pad_gap(btn_cont, 20, LV_PART_MAIN);
    
    // 悔棋按钮
    lv_obj_t* undo_btn = lv_btn_create(btn_cont);
    lv_obj_set_size(undo_btn, 180, 50);
    lv_obj_set_style_bg_color(undo_btn, lv_color_hex(0x4A6572), LV_PART_MAIN);
    lv_obj_set_style_radius(undo_btn, 10, LV_PART_MAIN);
    
    lv_obj_t* undo_label = lv_label_create(undo_btn);
    lv_label_set_text(undo_label, "悔棋");
    lv_obj_set_style_text_font(undo_label, &lv_mygec_font, LV_PART_MAIN);
    lv_obj_center(undo_label);
    lv_obj_add_event_cb(undo_btn,undo_btn_op,LV_EVENT_CLICKED,NULL);
    


    // 重新开始按钮
    lv_obj_t* restart_btn = lv_btn_create(btn_cont);
    lv_obj_set_size(restart_btn, 180, 50);
    lv_obj_set_style_bg_color(restart_btn, lv_color_hex(0x4A6572), LV_PART_MAIN);
    lv_obj_set_style_radius(restart_btn, 10, LV_PART_MAIN);
    
    lv_obj_t* restart_label = lv_label_create(restart_btn);
    lv_label_set_text(restart_label, "退出");
    lv_obj_set_style_text_font(restart_label, &lv_mygec_font, LV_PART_MAIN);
    lv_obj_center(restart_label);

     lv_obj_add_event_cb(restart_btn,restart_btn_op,LV_EVENT_CLICKED,NULL);


    // 再来一局按钮
    lv_obj_t* newgame_btn = lv_btn_create(btn_cont);
    lv_obj_set_size(newgame_btn, 180, 50);
    lv_obj_set_style_bg_color(newgame_btn, lv_color_hex(0x4A6572), LV_PART_MAIN);
    lv_obj_set_style_radius(newgame_btn, 10, LV_PART_MAIN);
    
    lv_obj_t* newgame_label = lv_label_create(newgame_btn);
    lv_label_set_text(newgame_label, "再来一局");
    lv_obj_set_style_text_font(newgame_label, &lv_mygec_font, LV_PART_MAIN);
    lv_obj_center(newgame_label);

    lv_obj_add_event_cb(newgame_btn,newgame_btn_op,LV_EVENT_CLICKED,NULL);



    // 对局信息
    lv_obj_t* info_panel = lv_obj_create(panel);
    lv_obj_set_size(info_panel, 320 - 40, 150);
    lv_obj_align(info_panel, LV_ALIGN_BOTTOM_MID, 0, -20);
    lv_obj_set_style_bg_color(info_panel, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
    lv_obj_set_style_radius(info_panel, 10, LV_PART_MAIN);
    lv_obj_set_style_pad_all(info_panel, 15, LV_PART_MAIN);
    
  
    
    // 对局信息内容
    info_label = lv_label_create(info_panel);
    lv_label_set_text(info_label,"游戏开始");
     lv_obj_set_style_text_font(info_label, &lv_mygec_font, LV_PART_MAIN); 
    lv_obj_align(info_label, LV_ALIGN_TOP_LEFT, 0, 35);
    lv_obj_set_style_text_line_space(info_label, 8, LV_PART_MAIN);


}
// 更新对局信息函数
void update_game_info()
{
     //pthread_mutex_lock(&ui_mutex);
    if (info_label) {
        lv_label_set_text(info_label, checkwin());
      //  lv_refr_now(NULL);  // 强制刷新显示
    }
     //pthread_mutex_unlock(&ui_mutex);
}

/*void update_game_info()
{
    if (info_label) {
        
        char buffer[128];  // 确保足够容纳所有文本

        // 使用snprintf安全格式化（\n实现换行）
        snprintf(buffer, sizeof(buffer),
        "坐标 (%d %d)\n"     // \n 表示换行
        "步数: %d\n"
        "状态: %s",
        global_list->last.x,global_list->last.y,global_list->num, checkwin());
        lv_label_set_text(info_label, buff);
        lv_refr_now(NULL);  // 强制刷新显示
    }
}
*/   


char *checkwin()
{

    // 检查四个方向: 水平、垂直、对角线(左上-右下)、反对角线(右上-左下)
    const int dx[] = {1, 0, 1, 1};
    const int dy[] = {0, 1, 1, -1};

    for (int y = 0; y <15; y++) 
    {
        for (int x = 0; x < 15; x++) 
        {
            int cell = board_state[y][x];
            if (cell == 0) continue; // 空位跳过

            for (int dir = 0; dir < 4; dir++) {
                int count = 1; // 当前棋子已计数
                
                // 正向检查
                for (int step = 1; step < 5; step++) 
                {
                    int nx = x + dx[dir] * step;
                    int ny = y + dy[dir] * step;
                    
                    if (nx < 0 || nx >= 15|| ny < 0 || ny >= 15) 
                        break;
                    if (board_state[ny][nx] != cell) 
                        break;
                        
                    count++;
                }
                
                // 反向检查
                for (int step = 1; step < 5; step++) 
                {
                    int nx = x - dx[dir] * step;
                    int ny = y - dy[dir] * step;
                    
                    if (nx < 0 || nx >= 15 || ny < 0 || ny >= 15) 
                        break;
                    if (board_state[ny][nx] != cell) 
                        break;
                        
                    count++;
                }
                
                // 五连珠判断
                if (count >= 5)
                {
                    game_over = 1;
                    return (cell == 1) ? "黑棋胜利!" : "白棋胜利!";
                }
            }
        }
    }
    
    // 检查平局 (棋盘已满)
    if (global_list->num>= 15 * 15) 
    {
        game_over = 1;
        return "和棋!";
    }
      
    if (global_list->num == 0|| !info_label) {
        return "开始"; // 黑棋先行
    }
    // 游戏继续
    return (global_list->last && global_list->last->type == 0) ? "白棋" : "黑棋";
}

void undo_btn_op(lv_event_t *e)//悔棋
{    
    if (global_list->num > 0) {
        Node* p = global_list->last;
          // 处理链表指针
        if (global_list->num == 1) {  // 最后一个节点
            global_list->first = NULL;
            global_list->last = NULL;
        } else {
            global_list->last = p->prev;
            global_list->last->next = NULL;
        }
        
        // 获取棋盘位置
        int board_x = p->x / 32;
        int board_y = p->y / 32;
        
        // 更新棋盘状态
        board_state[board_y][board_x] = 0;
        
        // 删除对象
        lv_obj_del(p->img);
        free(p);
        global_list->num--;
    }
    game_over = 0;
    update_game_info();
}





void newgame_btn_op(lv_event_t *e)//再来一局
{    
     while (global_list->num > 0) 
    {
        undo_btn_op(e);
    }
    
    // 重置棋盘状态
    memset(board_state, 0, sizeof(board_state));
    game_over = 0;
    update_game_info();
}

void restart_btn_op(lv_event_t *e)//退出
{     
   // 不再调用 exit(0)，而是清理游戏资源
    while (global_list->num > 0) 
    {
        undo_btn_op(e);
    }
    
    // 重置棋盘状态
    memset(board_state, 0, sizeof(board_state));
    game_over = 0;
    
    //删除游戏UI
    lv_obj_del(board);
    lv_obj_del(chess_bg);
    lv_obj_del( panel); // 删除控制面板
    board=NULL;
   chess_bg=NULL;
    panel=NULL;
    if(global_list) {
        free(global_list);
        global_list = NULL;
    }
    //pthread_cancel(tid1);
    game_ui_requested=1;
    lv_obj_remove_flag(app_container, LV_OBJ_FLAG_HIDDEN);

    // pthread_join(tid1,NULL);
    
    // 通知主线程线程结束
    
}
lv_obj_t* board1;
lv_obj_t *chess_bg1;

void start(lv_event_t *e)
{    
   lv_obj_del(board1);
   lv_obj_del(chess_bg1);
   board1=NULL;
   chess_bg1=NULL;
}
void gamestart(lv_obj_t* parent)
{
    
    // 棋盘背景
    board1 = lv_obj_create(parent);
    lv_obj_set_size(board1, 800, 480);
    lv_obj_set_pos(board1, 0, 0);
    lv_obj_set_style_bg_color(board1, lv_color_hex(0xD2B48C), LV_PART_MAIN);
    lv_obj_set_style_border_width(board1, 0, LV_PART_MAIN);
    lv_obj_set_style_radius(board1, 0, LV_PART_MAIN);
     lv_obj_add_event_cb(board1,start,LV_EVENT_CLICKED,NULL);
    
   chess_bg1= lv_img_create(lv_scr_act());
   lv_img_set_src(chess_bg1, "A:/tzh/start.bmp");
   

    
}
